package com.fruit.system.advice;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StringUtils;

import com.fruit.auth.model.User;
import com.fruit.system.model.Log;
import com.fruit.system.service.LogService;
import com.opensymphony.xwork2.ActionContext;
/**
 * 记录操作
 * @author Administrator
 *
 */
public class Logger
{
	private LogService logService;
	public void setLogService(LogService logService)
	{
		this.logService = logService;
	}
	public Object record(ProceedingJoinPoint point)
	{
		Log log=new Log();
		try
		{
			//设置操作人
			ActionContext context=ActionContext.getContext();
			if(null!=context)
			{
				HttpServletRequest req=(HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
				User user=(User) req.getSession().getAttribute("user");
				if(null!=user)
				{
					log.setOperator(""+user.getId()+","+user.getEmail()+","+user.getNickname());
					
				}
					
			}
			//设置操作方法
			String methodName=point.getSignature().getName();
			log.setOperName(methodName);
			//设置操作参数
			Object[] args=point.getArgs();
			log.setOperParams(StringUtils.arrayToCommaDelimitedString(args));
			//调用目标对象的方法
			Object result=point.proceed();
			//设置操作结果
			log.setOperResult("success");
			//设置操作结果消息
			if(null!=result)
			{
				log.setResultMsg(result.toString());
			}
			return result;
			
		}
		catch (Throwable e)
		{
			log.setOperResult("failure");
			log.setResultMsg(e.getMessage());
		}
		finally
		{
			//保存log到数据库
			logService.saveLog(log);
		}
		return null;
	}
}
